import React, { useState,useEffect } from 'react';
import { Form, Row, Col, Input, Button,Select,TreeSelect,Table, InputNumber, Popconfirm, Typography,Modal } from 'antd';
import {DivStyle} from "./style"
import { getStafflist } from "../../../model/staffModel"
import { useDispatch,useSelector } from "react-redux"
import AddStaff from "./ui/addStaff"
const { Option } = Select;

//表格部分
let originData = [{key:1,staffNumber:12,name:"liwenjie",account:123,department:"行政部",post:"销售经理",phonenumber:13254628595,status:"在职","addTime":"20170210"}];


const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};



const AdvancedSearchForm = () => {
  //redux中的数据
  const dispatch = useDispatch()
  const stafflist= useSelector(state => state.getIn(["staff"])).toJS()


  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [form] = Form.useForm();

  //获取stafflist数据的函数
  async function getstaffMsg(){
      let data = await getStafflist()
      setData(data)
      dispatch({
        type: 'stafflist',
        data
      })
    }
  //模拟componentDidMount生命周期函数
  useEffect(() => {
    getstaffMsg()
  }, []);

  //表格部分
  const [editingKey, setEditingKey] = useState('');
  //表格数据
  const [ data,setData ] = useState(originData)

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: '',
      age: '',
      address: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        dispatch({
          type: 'stafflistUpdate',
          data:newData
        })
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        console.log(newData)
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const columns = [
    {
      title: '员工编号',
      dataIndex: 'staffNumber',
      width: '10%',
      editable: true,
    },
    {
      title: '员工姓名',
      dataIndex: 'name',
      width: '10%',
      editable: true,
    },
    {
      title: '员工账号',
      dataIndex: 'account',
      width: '10%',
      editable: true,
    },
    {
      title: '所属部门',
      dataIndex: 'department',
      width: '10%',
      editable: true,
    },
    {
      title: '员工职位',
      dataIndex: 'post',
      width: '10%',
      editable: true,
    },
    {
      title: '电话号码',
      dataIndex: 'phonenumber',
      width: '15%',
      editable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '10%',
      editable: true,
    },
    {
      title: '添加时间',
      dataIndex: 'addTime',
      width: '15%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              href="javascript:;"
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </a>
            <Popconfirm title="确定修改?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            修改
          </Typography.Link>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'addTime' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  //拟态框
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = React.useState('Content of the modal');
  const superAdd = (a)=>{
    setData([...data,a])
  }
  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setConfirmLoading(false);
    }, 1000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setVisible(false);
  };


  const onFinish = (values) => {
    console.log(values);
    let newd=data;
    for(let key in values){
      if(values[key]!==undefined){
         newd = newd.filter(item=>{
           return item[key] === values[key]
        })
      }
    }
    setData(newd)
  };
  //每一个form都要指定from名
  const [form2] = Form.useForm();
  return (
      <DivStyle>
          <div className = "header">
          <Form
                form={form2}
                name="stuff_search"
                className="ant-advanced-search-form"
                onFinish={onFinish}
              >
      <Row gutter={24}>
            <Col span={6} key={1}>
                <Form.Item
                    name={`account`}
                    label={`员工账号`}
                    rules={[
                    {
                        required: false,
                        message: 'Input something!',
                    },
                    ]}
                >
                    <Input placeholder="请输入员工账号" />
                </Form.Item>
                </Col>

                <Col span={6} key={2}>
                <Form.Item
                    name={`name`}
                    label={`员工姓名`}
                    rules={[
                    {
                        required: false,
                        message: 'Input something!',
                    },
                    ]}
                >
                    <Input placeholder="请输入员工姓名" />
                </Form.Item>
                </Col>

                <Col span={6} key={3}>
                <Form.Item 
                name={`post`}
                label="员工职位">
                    <TreeSelect
                      treeData={[
                        {
                          value: '项目经理',
                          label: '项目经理',
                        },
                        {
                          value: '销售经理',
                          label: '销售经理',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>

                <Col span={6} key={4}>
                <Form.Item 
                name={`status`}
                label="员工状态">
                    <TreeSelect
                      treeData={[
                        {
                          value: '在职',
                          label: '在职',
                        },
                        {
                          value: '离职',
                          label: '离职',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>
      </Row>
      <Row>
        <Col span={2} style={{flex:"0 0 6%"}}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          </Col>
          {/* //清除搜索条件进行还原 */}
          <Col span={2}>
          <Button
    
            onClick={() => {
              form2.resetFields();
              setData(stafflist.stafflist)
            }}
          >
            清空条件
          </Button>
        </Col>
        {/* //添加按钮 */}
        <Col span={2}>
            <>
              <Button type="primary" onClick={showModal}>
                新增
              </Button>
              <Modal
                title="新增员工信息"
                visible={visible}
                onOk={handleOk}
                footer={null}
               confirmLoading={confirmLoading}
                onCancel={handleCancel}
                bodyStyle={{"width":"100%"}}
              >
                <AddStaff fn ={handleOk} fn2 ={handleCancel} fn3={superAdd}/>
              </Modal>
            </>
        </Col>
      </Row>
    </Form>
          </div>
          <div className = "table">
            <Form form={form} component={false}>
              <Table
                components={{
                  body: {
                    cell: EditableCell,
                  },
                }}
                bordered
                dataSource={data}
                columns={mergedColumns}
                rowClassName="editable-row"
                //设置为每页八条数据
                pagination={{
                  defaultPageSize:8
                }}
              />
            </Form>
          </div>
      </DivStyle>
  );
};

export default AdvancedSearchForm 